package com.wang.html2richtext.utils;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileUtil {

    private static String imgFix = ".jpg";

    public  static Map<String, String> keyValueMap = new HashMap<>();

    public static String getPicture(String url, String filePath, String filePathStart) {

        String fileName = UUID.randomUUID().toString().replace("-","");
        File imgFileDir = new File(filePath);
        if(!imgFileDir.exists()){
            imgFileDir.mkdirs();
        }
        String fullFilePath = filePath + fileName + imgFix ;
        if (!url.equals("")) {
            URL ur;
            BufferedInputStream in;
            ByteArrayOutputStream outStream;
            try {
                ur = new URL(url);
                in = new BufferedInputStream(ur.openStream());
                outStream = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int length = 0;
                while ((length = in.read(buf, 0, buf.length)) != -1) {
                    outStream.write(buf, 0, length);
                }
                byte[] bytes = outStream.toByteArray();
                File fileOut = new File(fullFilePath);
                FileOutputStream op = new FileOutputStream(fileOut);

                op.write(bytes);
                op.close();
                in.close();
                outStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            keyValueMap.put(url, filePathStart + fileName + imgFix);
        }
        System.out.println("result data-src:" + filePathStart + fileName + imgFix);
        return  filePathStart + fileName + imgFix;
    }
}
